package com.jsh.erp.service.cheque;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.dao.mappers.ChequeMapper;
import com.jsh.erp.dao.mappers.ChequeMapperEx;
import com.jsh.erp.dao.mappers.DepotItemMapperEx;
import com.jsh.erp.domain.entities.*;
import com.jsh.erp.domain.param.ChequeReportParam;
import com.jsh.erp.domain.vo.ChequeReport;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.utils.ExceptionUtil;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.TokenUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ChequeService {

    private Logger logger = LoggerFactory.getLogger(ChequeService.class);

    @Autowired
    private ChequeMapperEx chequeMapperEx;

    @Autowired
    private ChequeMapper chequeMapper;
    @Resource
    private LogService logService;

    @Autowired
    private DepotItemMapperEx depotItemMapperEx;

    public List<Cheque> getList(String chequeNum) {
        if (!StringUtils.isEmpty(chequeNum)) {
            List<String> list = Arrays.asList(chequeNum.split(","));
            return chequeMapperEx.selectByChequeNums(list);
        }
        return new ArrayList<>();
    }

    public Cheque getById(Long id) {
        return null;
    }

    public List<ChequeEx> select(String chequeNumber, String beginTime, String endTime, Long organId, Long creator, Long handsPersonId, Long accountId, String status, String remark, int offset, int rows) {
        List<ChequeEx> result = new ArrayList<>();
        try {
            ChequeQuery chequeQuery = new ChequeQuery();

            if (!StringUtils.isEmpty(chequeNumber)) {
                chequeQuery.setChequeNumber(chequeNumber);
            }
            if (!StringUtils.isEmpty(beginTime)) {
                beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
                endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
                chequeQuery.setBeginTime(beginTime);
                chequeQuery.setEndTime(endTime);
            }
            if (organId != null) {
                chequeQuery.setSupplierId(organId);
            }
            if (creator != null) {
                chequeQuery.setCreator(creator);
            }
            if (handsPersonId != null) {
                chequeQuery.setHandsPersonId(handsPersonId);
            }
            if (accountId != null) {
                chequeQuery.setAccountId(accountId);
            }
            if (!StringUtils.isEmpty(status)) {
                chequeQuery.setStatus(Integer.valueOf(status));
            }
            if (!StringUtils.isEmpty(remark)) {
                chequeQuery.setRemark(remark);
            }
            chequeQuery.setOffset(offset);
            chequeQuery.setRows(rows);
            List<ChequeEx> cheques = chequeMapperEx.selectByChequeQuery(chequeQuery);
            if (!CollectionUtils.isEmpty(cheques)) {
                for (ChequeEx cheque : cheques) {
                    if (cheque.getCreateTime() != null) {
                        cheque.setCreateTimeStr(Tools.dateToStr(cheque.getCreateTime(), "yyyy-MM-dd"));
                    }
                }


                result = cheques;
            }
        } catch (Exception e) {
            ExceptionUtil.readFail(logger, e);
        }
        return result;
    }

    public Long countCheque(String chequeNumber, String beginTime, String endTime, Long organId, Long creator, Long handsPersonId, Long accountId, String status, String remark, int offset, int rows) {
        Long count = 0L;
        try {
            ChequeQuery chequeQuery = new ChequeQuery();
            if (!StringUtils.isEmpty(chequeNumber)) {
                chequeQuery.setChequeNumber(chequeNumber);
            }
            if (!StringUtils.isEmpty(beginTime)) {
                beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
                endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
                chequeQuery.setBeginTime(beginTime);
                chequeQuery.setEndTime(endTime);
            }
            if (organId != null) {
                chequeQuery.setSupplierId(organId);
            }
            if (creator != null) {
                chequeQuery.setCreator(creator);
            }
            if (handsPersonId != null) {
                chequeQuery.setHandsPersonId(handsPersonId);
            }
            if (accountId != null) {
                chequeQuery.setAccountId(accountId);
            }
            if (!StringUtils.isEmpty(status)) {
                chequeQuery.setStatus(Integer.valueOf(status));
            }
            if (!StringUtils.isEmpty(remark)) {
                chequeQuery.setRemark(remark);
            }
            chequeQuery.setOffset(offset);
            chequeQuery.setRows(rows);
            Long c = chequeMapperEx.countByChequeQuery(chequeQuery);
            if (c != null) {
                count = c;
            }
        } catch (Exception e) {
            ExceptionUtil.readFail(logger, e);
        }
        return count;
    }

    //    {"organId":73,"issueDate":"2024-08-25 22:04:22","chequeNumber":"asss44555","handsPersonId":20,"accountId":21,"payeeName":"阿达",
//    "amount":"1234","bankName":"顶顶顶","returnReason":"a d1","remark":"ff"}
    public int insertCheque(JSONObject obj, HttpServletRequest request) {
        Cheque cheque = JSONObject.parseObject(obj.toJSONString(), Cheque.class);
        if (checkIsNoExist(cheque.getChequeNumber()) > 0) {
            throw new DuplicateKeyException("insertCheque error");
        }

        cheque.setCreator(TokenUtil.parseTokenFromRequest().getUserId());
        //已兑现状态的支票需要审核一次
        if (cheque.getStatus() == 1) {
            cheque.setApproveStatus(1);
        }
        return chequeMapper.insertSelective(cheque);
    }

    public int checkIsNoExist(String chequeNumber) {
        ChequeExample chequeQuery = new ChequeExample();

        if (!StringUtils.isEmpty(chequeNumber)) {
            chequeQuery.createCriteria().andChequeNumberEqualTo(chequeNumber).andDeleteFlagEqualTo(0);
        }
        List<Cheque> cheques = chequeMapper.selectByExample(chequeQuery);
        return cheques.size();
    }

    public int checkIsNameExist(Long id, String name) {
        return 0;
    }

    public int batchDeleteCheque(String ids, HttpServletRequest request) {
        List<Long> idList = StringUtil.strToLongList(ids);
        ChequeExample example = new ChequeExample();
        example.createCriteria().andIdIn(idList);
        int result = 0;
        try {
            result = chequeMapper.deleteByExample(example);
            logService.insertLog("支票管理", "批量删除,id集:" + ids, request);
        } catch (Exception e) {
            ExceptionUtil.writeFail(logger, e);
        }
        return result;
    }

    public int deleteCheque(Long id, HttpServletRequest request) {
        int result = 0;
        if (id != null) {
            try {
                result = chequeMapper.deleteByPrimaryKey(id);
                logService.insertLog("支票管理", "批删除,id:" + id, request);
            } catch (Exception e) {
                ExceptionUtil.writeFail(logger, e);
            }
        }
        return result;
    }

    public int updateCheque(JSONObject obj, HttpServletRequest request) {
        Cheque cheque = JSONObject.parseObject(obj.toJSONString(), Cheque.class);

        //已兑现状态的支票需要审核一次
        if (cheque.getStatus() == 1) {
            cheque.setApproveStatus(1);
        }
        int result = 0;
        try {
            result = chequeMapper.updateByPrimaryKeySelective(cheque);
            logService.insertLog("支票",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(cheque.getChequeNumber()).toString(), request);
        } catch (Exception e) {
            ExceptionUtil.writeFail(logger, e);
        }
        return result;
    }

    public List<ChequeReport> getReport(ChequeReportParam param) {
        if (!StringUtils.isEmpty(param.getBeginTime())) {
            param.setBeginTime(Tools.parseDayToTime(param.getBeginTime(), BusinessConstants.DAY_FIRST_TIME));
        }
        if (!StringUtils.isEmpty(param.getEndTime())) {
            param.setEndTime(Tools.parseDayToTime(param.getEndTime(), BusinessConstants.DAY_LAST_TIME));
        }
        List<ChequeReport> list = chequeMapperEx.getReport(param);
        if (!CollectionUtils.isEmpty(list)) {
            for (ChequeReport chequeReport : list) {
                if (chequeReport.getBillId() != null) {
                    List<DepotItemVo4WithInfoEx> detailList = depotItemMapperEx.getDetailList(Long.valueOf(chequeReport.getBillId()));
                    if (!CollectionUtils.isEmpty(detailList)) {
                        chequeReport.setMaterialInfo(detailList.get(0).getMName());
                    }
                }
            }
        }
        return list;
    }

    public Long countReport(ChequeReportParam param) {
        if (!StringUtils.isEmpty(param.getBeginTime())) {
            param.setBeginTime(Tools.parseDayToTime(param.getBeginTime(), BusinessConstants.DAY_FIRST_TIME));
        }
        if (!StringUtils.isEmpty(param.getEndTime())) {
            param.setEndTime(Tools.parseDayToTime(param.getEndTime(), BusinessConstants.DAY_LAST_TIME));
        }
        Long l = chequeMapperEx.getReportCount(param);
        return l == null ? 0 : l;
    }

    public int batchSetStatus(Integer status, String ids) {
        logService.insertLog("支票管理",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        List<Long> chequeIds = StringUtil.strToLongList(ids);
        Cheque cheque = new Cheque();
        cheque.setApproveStatus(status);
        ChequeExample example = new ChequeExample();
        example.createCriteria().andIdIn(chequeIds);
        int result = 0;
        try {
            result = chequeMapper.updateByExampleSelective(cheque, example);
        } catch (Exception e) {
            ExceptionUtil.writeFail(logger, e);
        }
        return result;
    }
}
